import os, re
from csvtosql2 import csv_read2
from upload import upload_csv
from app import logger


def read_file(path, name_list, moid_list):
    file_list = os.listdir(path)
    # print(file_list)
    for file in file_list:
        file = os.path.join(path, file)
        if os.path.isdir(file):  # 下一级是文件夹
            file_name = os.path.join(path, file)
            read_file(file_name, name_list, moid_list)
        else:
            file_name = os.path.splitext(os.path.basename(file))[0]
            # todo:这个条件匹配所有文件
            # if re.match('\w{5}-(.*)-\d', file_name):
            # todo:这个条件匹配Excel文件
            if re.match(r'Result_\d{8}-.*', file_name) and os.path.splitext(file)[1] == '.csv':
                moid = re.match(r'Result_(\d{8})-.*', file_name)
                name_list.append(os.path.join(path, file))
                moid_list.append('5102-' + moid.group(1))
    return name_list, moid_list


def upload(path, moid, num=0):
    # '焊线推力-齐纳',
    for i in ['焊线拉力-齐纳', '焊线推力-齐纳']:
        df, list_df, row_num, rest_num = csv_read2(path, i)
        if type(list_df) is list and list_df and not row_num and not rest_num:
            num += 1
            # print(df)
            # print(f"锚点1：文件路径：{path}")
            # print(f"锚点2：工单号：{moid}")
            # print(f"锚点3：类型：{i}")
            upload_csv(i, '11068', list_df, moid, None, logger)
        elif not list_df and row_num and not rest_num:
            print(f"锚点1：类型：{i}")
            print(f"锚点2：文件路径：{path}---{row_num}")

        else:
            continue
    return num


if __name__ == '__main__':
    name_list, moid_list = read_file(r'E:\Desktop\Work\Shear_pullAPP\2020橙光推拉数据', [], [])
    print(len(name_list))
    # print(moid_list)
    num2 = 1
    for name, moid in zip(name_list, moid_list):
        num = upload(name, moid)
        num2 += num
    print(f"锚点4：符合文件个数：{num2}")
